package definition

import (
	"fmt"
	"os"
	"path/filepath"
)

func ForeachFileRecursively(dir string, check func(string) bool, fn func(dir, filename string) error) error {
	listFe, err := os.ReadDir(dir)
	if err != nil {
		return err
	}

	for _, fe := range listFe {
		if fe.IsDir() {
			if GlobalConfig.Verbose {
				fmt.Println("Scan dir: ", filepath.Join(dir, fe.Name()))
			}
			if err := ForeachFileRecursively(filepath.Join(dir, fe.Name()), check, fn); err != nil {
				return err
			}
			continue
		}

		if !check(fe.Name()) {
			if GlobalConfig.Verbose {
				fmt.Println("Skip file: ", filepath.Join(dir, fe.Name()))
			}
			continue
		}

		if err := fn(dir, filepath.Join(fe.Name())); err != nil {
			return err
		}
	}

	return nil
}
